package com.ruoyi.web.controller.knowledge;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.law_model.knowledge.domain.DocumentSplit;
import com.ruoyi.law_model.knowledge.domain.KnowledgeDocuments;
import com.ruoyi.law_model.knowledge.service.IDocumentSplitService;
import com.ruoyi.law_model.knowledge.service.IKnowledgeDocumentsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 存储知识库中的文档信息Controller
 *
 * @author ruoyi
 * @date 2025-01-10
 */
@RestController
@RequestMapping("/knowledge/documents")
public class KnowledgeDocController extends BaseController
{
    @Autowired
    private IKnowledgeDocumentsService knowledgeDocumentsService;
    @Autowired
    private IDocumentSplitService documentSplitService;

    /**
     * 查询存储知识库中的文档信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:documents:list')")
    @GetMapping("/list")
    public TableDataInfo list(KnowledgeDocuments knowledgeDocuments)
    {
        startPage();
        List<KnowledgeDocuments> list = knowledgeDocumentsService.selectKnowledgeDocumentsList(knowledgeDocuments);
        return getDataTable(list);
    }

    /**
     * 导出存储知识库中的文档信息列表
     */
    @PreAuthorize("@ss.hasPermi('knowledge:documents:export')")
    @Log(title = "存储知识库中的文档信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KnowledgeDocuments knowledgeDocuments)
    {
        List<KnowledgeDocuments> list = knowledgeDocumentsService.selectKnowledgeDocumentsList(knowledgeDocuments);
        ExcelUtil<KnowledgeDocuments> util = new ExcelUtil<KnowledgeDocuments>(KnowledgeDocuments.class);
        util.exportExcel(response, list, "存储知识库中的文档信息数据");
    }

    /**
     * 获取存储知识库中的文档信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('knowledge:documents:query')")
    @GetMapping(value = "/{docId}")
    public AjaxResult getInfo(@PathVariable("docId") Long docId)
    {
        return success(knowledgeDocumentsService.selectKnowledgeDocumentsByDocId(docId));
    }

    /**
     * 新增存储知识库中的文档信息
     */
    @PreAuthorize("@ss.hasPermi('knowledge:documents:add')")
    @Log(title = "存储知识库中的文档信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KnowledgeDocuments knowledgeDocuments)
    {
        return toAjax(knowledgeDocumentsService.insertKnowledgeDocuments(knowledgeDocuments));
    }

    /**
     * 修改存储知识库中的文档信息
     */
    @PreAuthorize("@ss.hasPermi('knowledge:documents:edit')")
    @Log(title = "存储知识库中的文档信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KnowledgeDocuments knowledgeDocuments)
    {
        return toAjax(knowledgeDocumentsService.updateKnowledgeDocuments(knowledgeDocuments));
    }

    /**
     * 删除存储知识库中的文档信息
     */
    @PreAuthorize("@ss.hasPermi('knowledge:documents:remove')")
    @Log(title = "存储知识库中的文档信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{docIds}")
    public AjaxResult remove(@PathVariable Long[] docIds)
    {
        //不能批量删除
        if (docIds.length > 1) {
            return AjaxResult.error("不支持批量删除文档！");
        }
        return toAjax(knowledgeDocumentsService.deleteKnowledgeDocumentsByDocIds(docIds));
    }

    @Log(title = "知识库文档上传", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('knowledge:documents:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, long klId) throws Exception
    {
        // 从文件名字中解析文件类型
        String docType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1,file.getOriginalFilename().length());
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        } catch (Exception e) {
            throw new RuntimeException("读取文件失败", e);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        KnowledgeDocuments knowledgeDocuments = new KnowledgeDocuments();
        knowledgeDocuments.setKlId(klId);
        knowledgeDocuments.setDocumentName(file.getOriginalFilename());
        knowledgeDocuments.setDocumentType("文档");
        knowledgeDocuments.setDocumentFormat(docType);
        knowledgeDocuments.setDocumentPath("");
        knowledgeDocuments.setWebUrl("");
        knowledgeDocuments.setParsingStatus("1");
        knowledgeDocuments.setDocumentSize(file.getSize());
        knowledgeDocuments.setCharacterCount((long) contentBuilder.toString().length());
        knowledgeDocuments.setCreatedBy(String.valueOf(loginUser.getUserId()));
        knowledgeDocuments.setCreatedAt(new Date());
        knowledgeDocuments.setUpdatedAt(knowledgeDocuments.getCreatedAt());
        knowledgeDocuments.setUpdatedBy(String.valueOf(loginUser.getUserId()));
        knowledgeDocuments.setContent(contentBuilder.toString());
        knowledgeDocumentsService.insertKnowledgeDocuments(knowledgeDocuments);
        return success("上传成功");
    }
}
